//
//  Status.swift
//  01MicroBlog
//
//  Created by Apple on 15/8/2.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit
import SDWebImage

class Status: NSObject {
    
    /// 微博创建时间
    var created_at: String?
    
    /// cell行高
    var rowHeight:CGFloat?
    
    /// 微博ID
    var id: Int = 0
    /// 微博信息内容
    var text: String?
    /// 微博来源
    var source: String?
    
    var retweeted_status:Status?
    /// 配图数组
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            
            if pic_urls?.count == 0 {
                return
            }
            
            // 实例化一个url数组
            storedURLs = [NSURL]()
            storedLargeURLs = [NSURL]()
            
            // 取出字典中的url地址字符串
            for dict in pic_urls! {
                if let urlStr = dict["thumbnail_pic"] {
                    storedURLs?.append(NSURL(string: urlStr as! String)!)
                    
                    let largeURL = urlStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    storedLargeURLs?.append(NSURL(string: largeURL)!)
                }
            }
        }
    }
    
    // 保存配图数组
    private var storedURLs: [NSURL]?
    
    // 配图数组, 计算性属性返回图片
    var pictureURLs: [NSURL]? {
        // 判断是否是转发微博
        // 原创，返回storedURLs ; 转发，返回 retweeted_status?.storedURLs
        return self.retweeted_status == nil ?  storedURLs : retweeted_status?.storedURLs
    }
    
    // 保存大图的图片数组
    private var storedLargeURLs:[NSURL]?
    
    // 返回大图的URL数组
    var pictureLargeURLs:[NSURL]? {
        return self.retweeted_status == nil ? storedLargeURLs : retweeted_status?.storedLargeURLs
    }
    
    /// 用户信息
    var user:User?
    
   class func loadStatusDataList(since_id:Int, max_id:Int,finished:(dataList:[Status]?, error:NSError?)->() ) {
        
        let tool = NetworkTools.sharedNetworkTools
        tool.loadStatuses(since_id, max_id:max_id) { (result, error) -> () in
            if error != nil {
                finished(dataList: nil, error: error)
                return
            }
            
            var list = [Status]()
            // 访问正确
            if let array = result?["statuses"] as? [[String: AnyObject]] {
                // 字典转模型
                for item in array {
                    let status = Status(dict: item)
                    
                    list.append(status)
                }
                
                // 计算缓存图片的大小
               self.cacheWebImage(list,finished: finished)
               
                // 有数据，可以返回
//                finished(dataList: list, error: nil)
                
            } else {
                finished(dataList: nil, error: nil)
            }
            
        }
        
    }
    
/// 计算缓存图片
    private class func cacheWebImage (statusList:[Status], finished:(dataList:[Status]?, error:NSError?)->()) {
        let group = dispatch_group_create()
        var dataLength = 0
        
        for status in statusList {
            
            guard let urls = status.pictureURLs else {
                continue
            }
            // 有图片的情况下
            for url in urls {
                
                // 进入队列组
                dispatch_group_enter(group)
                
                // 下载图片
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _ , _ , _ , _ ) -> Void in
                    
                    // 累加图片
                    if image != nil {
                        let imageData = UIImagePNGRepresentation(image)!
                        dataLength += imageData.length
                    }
                    
//                    print("计算图片的大小")
                    
                    // 离开任务组
                    dispatch_group_leave(group)
                    
                })

            }
            
        }
        
        // 等队列组中任务结束之后，这个方法会接受到消息
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            print("over----\(dataLength)")
            
            // 缓存好，才返回数据
            finished(dataList: statusList, error: nil)
        })
        
        
    }
    
    init(dict:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    
    }
    
    // 重写setValue 方法，将里面的user的值再转成user模型
    override func setValue(value: AnyObject?, forKey key: String) {
        
        // 如果key是user的话，单独处理
        if key == "user" {
            // 判断value是不是一个有效的字典
            if let dict = value as? [String:AnyObject] {
                // 创建用户数据
                self.user = User(dict: dict)
            }
            // WARNIng: - 注意，这里一定要return，不然下面的super会覆盖这个的方法
            return
        }
        
        if key == "retweeted_status" {
            if let dict = value {
                // 设置转发模型
                self.retweeted_status = Status(dict: dict as! [String : AnyObject])
            }
            return
        }
        
        super.setValue(value, forKey: key)
    }
    
    override var description:String {
        let keys = ["created_at", "id", "text", "source", "pic_urls", "user", "pictureURLs"]
        return "\(dictionaryWithValuesForKeys(keys))"
    }
    
}
